﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Golos.Helper;

namespace Golos.Tags.Http
{
    public partial class TagCacheServer
    {
        private void AddTags(HttpListenerContext context, ref int statusCode)
        {
            try
            {
                if (context.Request.QueryString.AllKeys.Contains("questionid")
                    && context.Request.InputStream != null)
                {
                    Guid questionId = new Guid(context.Request.QueryString["questionid"]);
                    List<string> tags = new List<string>();
                    using (Stream stream = context.Request.InputStream)
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            while (!reader.EndOfStream)
                            {
                                string tag = reader.ReadLine();
                                if (string.IsNullOrEmpty(tag))
                                    continue;
                                tags.Add(tag);
                            }
                        }
                    }
                    tagsCache.AddTags(questionId, tags);
                    statusCode = (int)HttpStatusCode.OK;
                    return;
                }
                statusCode = (int)HttpStatusCode.BadRequest;
            }
            catch (Exception exception)
            {
                LogClass.WriteErrorEntry(exception.ToString());
                statusCode = (int)HttpStatusCode.InternalServerError;
            }
        }
    }
}
